-- Viral Resistance - T-Engine 4 Module
-- Copyright (C) 2010 Mikolai Fajer
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.
--
-- Mikolai Fajer "yufra"
-- mfajer@gmail.com

local Astar = require "engine.Astar"

-- AI for the escort quest
-- the NPC will run toward the portal, if hostiles are in sight he attacks them
newAI("escort_quest", function(self)
	self.ai_target.actor = nil
	-- Check for a close hostile target
	if self:runAI("target_simple") and core.fov.distance(self.ai_target.actor.x, self.ai_target.actor.y, self.x, self.y) <= 4 then
		self:runAI("flee_dmap")
	-- Check for the closest broken conduit within LOS and 4 tiles
	else
		self.ai_target.actor = nil
		for i, spot in ipairs(game.level.spots) do
			if spot.type == 'quest' and spot.subtype == "broken_conduit" then
				if core.fov.distance(self.x, self.y, spot.x, spot.y) <=4 then
					self.ai_target.actor = {x=spot.x, y=spot.y}
				end
			end
		end
	end
	-- Otherwise make for the player
	if not self.ai_target.actor then
		self:runAI("target_player")
	end
	if not self.energy.used then
		local a = Astar.new(game.level.map, self)
		local path = a:calc(self.x, self.y, self.ai_target.actor.x, self.ai_target.actor.y)
		-- Run towards target
		if path then
			return self:move(path[1].x, path[1].y)
		-- Check if we can repair something
		else
			local quest = game.player:hasQuest("power_loss")
			if quest then
				quest:repair_conduit(self)
			end
			self:useEnergy()
		end
	end
end)